<template>
  <view class="weather-all">
    <!-- 收索 -->
    <view class="weather">
      <view class="font">
        您当前选择的位置为： <van-icon name="location-o" />{{ city }}
      </view>
      <uni-easyinput
        class="uni-mt-5"
        suffixIcon="search"
        v-model="value"
        trim="all"
        placeholder="点击图标搜索其他城市天气信息"
        placeholderStyle="font-size:20rpx"
        @iconClick="handleIconClick"
      ></uni-easyinput>
    </view>
    <!-- 七日天气预报 -->
    <view>
      <view class="weather-info" style="text-align: center; color: #fff">
        <view style="font-size: 36rpx; margin: 16rpx 0rpx">{{ city }}</view>
        <!-- {{ cityInfo[0].date }} -->
        <view>{{ cityInfo[0].week }}</view>
        <view style="font-size: 60rpx; margin: 16rpx 0rpx"
          >平均气温：{{ weather.average[0] || 0 }} °C</view
        >
        <view style="margin: 16rpx 0rpx"
          >{{ cityInfo[0].type || '' }} {{ cityInfo[0].fengxiang || '' }}
          {{ cityInfo[0].fengli || '' }}</view
        >
        <view>{{ cityInfo[0].low || '' }} ~ {{ cityInfo[0].high || '' }} </view>
      </view>
      <view class="weather-week">
        <uni-section
          titleColor="#fff"
          titleFontSize="40rpx"
          :title="`${city}周天气预报`"
        >
          <text style="color: #fff; margin-left: 26rpx">
            图表中所有单位均为°C
          </text>
          <!-- 折线图 -->
          <view class="charts-box">
            <qiun-data-charts type="line" :opts="opts" :chartData="chartData" />
          </view>
          <uni-card
            class="uni-card"
            :is-shadow="false"
            v-for="(item, index) in cityInfo"
            :key="index + Math.random()"
          >
            <view class="week-font">
              <text class="uni-body">
                <!-- {{ item.date }}   -->
                {{ item.week }}
              </text>
              <text style="margin-left: 20rpx" class="uni-body">{{
                item.type
              }}</text>
              <text style="margin-left: 20rpx" class="uni-body"
                >{{ item.fengxiang }}{{ item.fengli }}</text
              >
              <text style="margin-left: 20rpx" class="uni-body">
                {{ item.low }} ~ {{ item.high }}
              </text>
              <view class="uni-body"
                >夜间 {{ item.night.type }} {{ item.night.fengxiang }}
                {{ item.night.fengli }}</view
              >
            </view>
          </uni-card>
        </uni-section>
        <view style="height: 10rpx"></view>
      </view>
    </view>
  </view>
</template>

<script>
import mixin from "@/mixins/mixins.js";
export default {
  name: 'Weather',
  mixins: [mixin],
  data() {
    return {
      city: '', // 城市
      value: '', // 收索框
      oldCity: '', // 搜索前的城市
      cityInfo: [], // 城市天气信息
      weather: {
        // 天气相关信息
        high: [], // 最高气温
        low: [], // 最低气温
        average: [] // 平均气温
      },
      // 折线图相关配置
      chartData: {},
      opts: {
        color: ['#EE6666', '#9ab9f5', '#9A60B4', '#FAC858'],
        fontColor: '#fff',
        padding: [15, 15, 0, 5],
        enableScroll: false,
        legend: {},
        xAxis: {
          fontColor: '#fff',
          disableGrid: true,
          gridType: 'dash',
          boundaryGap: 'justify'
        },
        yAxis: {
          data: []
        },
        extra: {
          column: {
            type: 'group',
            width: 30,
            activeBgColor: '#000000',
            activeBgOpacity: 0.08,
            linearType: 'custom',
            seriesGap: 5,
            linearOpacity: 0.5,
            barBorderCircle: false,
            customColor: ['#FA7D8D', '#EB88E2']
          }
        }
      }
    }
  },
  created() {
    this.getWeatherList()
    this.getServerData()
  },
  mounted() {},
  methods: {
    // 进入页面根据当前位置获取天气
    async getWeatherList() {
      // 高德地图获取地理信息
      const cityInfo = await this.$http.get(
        'https://restapi.amap.com/v3/ip?key=d83332c6dec14bd1cd2e40a72c2e52f1'
      )
      // console.log(cityInfo)
      this.city = this.oldCity = cityInfo.city
      // 获取近7天天气
      const res = await this.$http.get(`/weather?city=${this.city}&type=week`)
      // console.log(res,'天气',this.city)
      if (res.success) {
        this.cityInfo = res.data
        // console.log(res)
        this.cityInfo[0].week = '今天'
        this.getWeather() // 截取温度
        this.getServerData() // 折线图
      } else {
        this.$msg('目前仅支持市级城市查询~请您精确到市名后重试')
      }
    },
    // 手动搜索位置
    async handleIconClick() {
      // 输入框内有数据
      if (this.value) {
        // 如果没有市，自动补市
        !this.value.includes('市') ? (this.value += '市') : this.value
        this.city = this.value
        // console.log(this.city.includes('市'), 36)
      } else {
        // 默认按照当前城市地点查询
        this.city = this.oldCity
        this.value = ''
      }
      // 重新获取天气信息
      const res = await this.$http.get(`/weather?city=${this.city}&type=week`)
      // console.log(res,177)
      // 请求发送成功
      if (res.success) {
        // console.log(res)
        this.cityInfo = res.data
        this.cityInfo[0].week = '今天'
        this.getWeather() // 截取温度
        this.getServerData() // 折线图
      } else {
        // 失败则恢复旧值并清空
        this.city = this.oldCity
        this.value = ''
        this.$msg('目前仅支持市级城市查询~请您精确到市名后重试')
      }
    },
    // 获取气温
    async getWeather() {
      // this.cityInfo[0].high = '最高 -100°C'
      // 获取最高和最低温度
      const res = await this.$http.get(`/weather?city=${this.city}&type=week`)
      // 重置数组，如果切换城市数据会叠加
      this.weather.average = []
      this.weather.high = []
      this.weather.low = []
      // 只取数字
      res.data.forEach((item) => {
        // 正则替换
        let high = item.high.replace('°C','')
        let low = item.low.replace('°C','')
        // 将字符串转为数字
        high = parseInt(high)
        low = parseInt(low)
        // this.weather.high = this.weather.low = []
        this.weather.high.push(high)
        this.weather.low.push(low)
        // console.log(high,low,321)
      })

      // 获取平均温度
      this.weather.high.forEach((high, index) => {
        const low = this.weather.low[index]
        this.weather.average.push((high + low) / 2) // 平均气温
        // console.log(high,low)
      })
      // console.log(this.weather)
    },
    async getServerData() {
      const res2 = await this.$http.get(`weather?city=${this.city}&type=week`)
      // const data = res2.data.map((item) => item.date.substring(5, 10))
      // res2.data第一次调用会为undefined 有报错，但不影响
      if (res2.success) {
        const data = res2.data.map((item) => item.week)
        let res = {
          categories: data,
          series: [
            {
              name: '最高温度',
              data: this.weather.high
            },
            {
              name: '最低温度',
              data: this.weather.low
            },
            {
              name: '平均温度',
              data: this.weather.average
            }
          ]
        }
        this.chartData = JSON.parse(JSON.stringify(res))
      }
      // console.log(data)
      // console.log(this.chartData.categories)
    },

  }
}
</script>

<style lang="scss" scoped>
// 修改搜索框相关样式
::v-deep .uni-easyinput {
  margin-left: 40rpx;
}
::v-deep .uni-easyinput__content {
  border-radius: 20rpx;
}
::v-deep .uni-section {
  background: none;
}
// 每一天的天气
::v-deep .uni-card {
  background: linear-gradient(35deg, #5987e5, #5987e5 35%, #6996f0);
}
.weather-all {
  .weather {
    display: flex;
    .font {
      // 左侧字体样式
      margin-top: 22rpx;
      margin-left: 22rpx;
      font-size: 24rpx;
    }
  }
  .weather-info {
    // 小程序不支持直接路径，需要转换为base64编码
    background: url('')
      no-repeat center;
    // background-size: 100% 100%;
  }
  .weather-week {
    // background: linear-gradient(35deg,#5987e5,#5987e5 35%,#6996f0);
    background: url()
      center;
    .uni-body {
      color: #fff;
    }
    /* 请根据实际需求修改父元素尺寸，组件自动识别宽高 */
    .charts-box {
      width: 100%;
      height: 350rpx;
    }
  }
}
</style>
